import React, { useContext, useState, useEffect, useRef } from 'react';
import { Input, Form } from 'antd';
import { SortableElement } from 'react-sortable-hoc';
import { TextWidget } from '@inbiz/react';
import MultilingualInput from '@inbiz/basic/MultilingualInput';
import { EditableContext } from './defaultOption';
import './defaultOption.less';

const SortableItem = SortableElement((props: any) => <tr {...props} />);

interface Item {
  id: string;
  key: string;
  name: string;
}

// 可修改表格组件-行
const EditableRow = (dataSource: object[]) => (props: any) => {
  const idx = dataSource?.findIndex((x: any) => x.id === props['data-row-key']);
  return <SortableItem index={idx} {...props} />;
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: string;
  record: Item;
  lang?: boolean;
  variateId: string;
  required: boolean;
  nowKey: string;
  setNowKey: (b: string) => void;
  handleSave: (record: Item) => void;
}

// 可修改表格组件-列（单元格）
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  lang,
  required,
  nowKey,
  setNowKey,
  handleSave,
  ...restProps
}: EditableCellProps) => {
  const [editing, $Editing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing && inputRef.current) {
      let dom: HTMLElement = inputRef.current;
      dom?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setNowKey(record.id);
    $Editing(true);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      let row: any = { ...record };
      handleSave({ ...row, ...values });
    } catch (err) { }
    $Editing(false);
  };

  let childNode = children;

  if (editable) {
    const placeMessage = '请输入';
    childNode =
      editing && nowKey === record.id ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={
            required
              ? [
                {
                  required: true,
                  message: `${title}为空`,
                },
              ]
              : []
          }
        >
          {['key', 'name'].includes(dataIndex) ? lang ? <MultilingualInput ref={inputRef} onPressEnter={save} onBlur={save} placeholder={placeMessage} /> : (
            <Input ref={inputRef} onPressEnter={save} onBlur={save} placeholder={placeMessage} />
          ) : null}
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          id={`cell-${dataIndex}-${record.id}`}
          onClick={toggleEdit}
        >
          {
            // @ts-ignore
            typeof (children?.[1]) == 'string' ?
              // @ts-ignore
              <TextWidget>{children[1]}</TextWidget>
              :
              children
          }
        </div>
      );
  }

  return <td {...restProps}>
    {
      // @ts-ignore
      typeof (childNode?.[1]) == 'string' ?
        // @ts-ignore
        <TextWidget>{childNode[1]}</TextWidget>
        :
        childNode
    }
  </td>;
};

export { EditableRow, EditableCell };
